/* eslint-disable no-unused-vars */
/* eslint-disable eqeqeq */
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'umi'
import { SaveOutlined } from '@ant-design/icons'
import { withI18n } from '@lingui/react'
import { Card, Form, Input, Button, message, Select, Modal } from 'antd'
import { tailLayout, layoutModel } from '@/utils/helper'
import { publicIp } from '@/services/apiIp'
import styles from './index.less'
import '@/utils/index.less'
import { get, post, put } from '@/services/https'
import { NAME, USERPWD } from '@/utils/regExp'
import { UploadOutlined } from '@ant-design/icons'
import Upload from '@/utils/Upload'
import { merge } from 'lodash'
import base64 from '@/utils/base64'
const { confirm } = Modal
let base = new base64()
const { Option } = Select
const { TextArea } = Input

// 1超级管理员 2系统管理员 3审计管理员 4安全管理员
@withI18n()
@connect(({ post, loading }) => ({ post, loading }))
class userDer extends React.Component {
  state = {
    fileName: '',
    pyCode: '',
    xmlCode: '',
    visible: false,
    mockData: [],
    mockDataclass: [],
    designwork_content: '',
    class_id: 1,
    classroom_id: 1,
    designwork_name: '',
    Myhomework: 0,
    visibles: false,
  }
  formRef = React.createRef()
  iframeRef = React.createRef()
  componentDidMount() {
    this.setState({ accessibility: sessionStorage.getItem('accessibility') })
    this.setState({ Myhomework: sessionStorage.getItem('Myhomework') })
    window.addEventListener('message', function (ev) {
      if (ev.data.code === 104) {
        that.setState({
          fileName: ev.data.param.fileName,
          pyCode: ev.data.param.pyCode,
          xmlCode: ev.data.param.xmlCode,
        })
      }
    })
    this.classlist()
    if (this.props.match.params.id && this.props.match.params.id != 0) {
      if (sessionStorage.getItem('Myhomework') == 0) {
        this.getData(this.props.match.params.id)
      } else {
        this.getDatas(this.props.match.params.id)
      }
    } else {
    }
    this.iframeRef.current.contentWindow.postMessage(
      publicIp,
      'https://online.mpython.cn/'
    )
    let that = this
    setTimeout(() => {
      if (that.props.match.params.id && that.props.match.params.id != 0) {
        that.clFna(4)
      } else {
        that.clFna(3)
      }
    }, 1000)
  }
  classlist = () => {
    post('class/list', {}).then((res) => {
      let data = res.data
      this.setState({ mockData: data })
    })
  }
  classlists = (class_id) => {
    post('dashboard/student/classroom/list', {}).then((res) => {
      let data = res.data
      this.setState({ mockDataclass: data })
    })
  }

  getData = (id) => {
    post('designwork/read', { id: id }).then((res) => {
      let data = res.data
      data.designwork_content = JSON.parse(data.designwork_content)
      this.setState({
        designwork_content: data.designwork_content,
        class_id: data.class_id,
        classroom_id: data.classroom_id,
        designwork_name: data.designwork_name,
        pyCode: window.atob(data.designwork_content.pyCode),
        xmlCode: window.atob(data.designwork_content.xmlCode)
      })
      // this.iframeRef.current.contentWindow.postMessage(
      //   { code: 1003, param: { data: data.designwork_content } },
      //   'https://online.mpython.cn/'
      // )
      if (window.atob(data.designwork_content.xmlCode) == '') {
        this.iframeRef.current.contentWindow.postMessage({ code: 1003, param: { data: window.atob(data.designwork_content.pyCode) } }, 'https://online.mpython.cn/')
      } else {
          this.iframeRef.current.contentWindow.postMessage({ code: 1003, param: { data: window.atob(data.designwork_content.xmlCode) } }, 'https://online.mpython.cn/')
      }
    })
  }
  getDatas = (id) => {
    post('dashboard/student/homework/read', { homework_id: id * 1 }).then((res) => {
      let data = res.data
      let homework_content = JSON.parse(data.homework_content)
      console.log(homework_content.pyCode)

      this.setState({
          homework_content: homework_content,
          pyCode: window.atob(homework_content.pyCode),
          xmlCode: window.atob(homework_content.xmlCode)
      })
      console.log(homework_content)
      if (window.atob(homework_content.xmlCode) == '') {
        this.iframeRef.current.contentWindow.postMessage({ code: 1003, param: { data: window.atob(homework_content.pyCode) } }, 'https://online.mpython.cn/')
      } else {
          this.iframeRef.current.contentWindow.postMessage({ code: 1003, param: { data: window.atob(homework_content.xmlCode) } }, 'https://online.mpython.cn/')
      }
      // this.iframeRef.current.contentWindow.postMessage(
      //   { code: 1003, param: { data: designwork_content } },
      //   'https://online.mpython.cn/'
      // )
    })
  }
  handleSaveBtn = (values) => { }
  clFna = (key) => {
    if (key == 1) {
      if(this.state.Myhomework == 0){
        this.props.history.push('/Myworks')
      } else{
        this.props.history.push('/Myhomework')
      }
    } else if (key == 3) {
      this.iframeRef.current.contentWindow.postMessage(
        { code: 1001 },
        'https://online.mpython.cn/'
      )
    } else if (key == 4) {
      if (this.state.xmlCode ==""){
        this.iframeRef.current.contentWindow.postMessage({ code: 1003, param: { data: this.state.pyCode } }, 'https://online.mpython.cn/')
    } else{
        this.iframeRef.current.contentWindow.postMessage({ code: 1003, param: { data: this.state.xmlCode } }, 'https://online.mpython.cn/')
    }
    } else if (key == 5) {
      this.props.history.push('/works/my')
    } else if (key == 6) {
      this.props.history.push('/programming')
    } else {
      this.props.history.push('/works/Show')
    }
  }
  Derive = () => {
    let Myhomework = this.state.Myhomework
    if (Myhomework == 0) {
      let that = this
      this.iframeRef.current.contentWindow.postMessage(
        { code: 1005 },
        'https://online.mpython.cn/'
      )
      this.setState({
        visible: true,
      })
      let initialValues = {
        classroom_id: '',
        designwork_name: '',
      }
      this.classlists(this.state.class_id)
      setTimeout(() => {
        that.formRef.current.setFieldsValue(initialValues)
      }, 100)
    } else {
      let that = this
      this.iframeRef.current.contentWindow.postMessage(
        { code: 1005 },
        'https://online.mpython.cn/'
      )
      this.setState({
        visibles: true,
      })
      confirm({
        title: '确定要提交作业吗?',
        content: '请确认',
        onOk() {
          let datas = {
            pyCode: btoa(that.state.pyCode),
            xmlCode: btoa(that.state.xmlCode)
        }
          let data = {
            homework_id: that.props.match.params.id * 1,
            homework_content: JSON.stringify(datas) //加密
          }
          post('dashboard/student/homework/submit', data).then((res) => {
            if (res.code === 0) {
              // message.success(i18n.t`The`)
              that.props.history.push('/Myhomework')
            } else {
              message.error(res.info)
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    }
  }
  Derive1 = () => {
    this.props.history.push('/Myworks')
  }
  Derive2 = () => {
    this.props.history.push('/DisplayWorks')
  }
  handleCancel = () => {
    this.setState({
      visible: false,
    })
  }
  handleOk = () => {
    const form = this.formRef.current
    var values = form.getFieldsValue(['designwork_name', 'classroom_id'])
    let datas = {
      pyCode: btoa(this.state.pyCode),
      xmlCode: btoa(this.state.xmlCode)
  }
    let data = {
      ...values,
      designwork_content: JSON.stringify(datas) //加密
    }
    if (this.props.match.params.id && this.props.match.params.id != 0) {
      data.id = this.props.match.params.id
      post('designwork/read', data).then((res) => {
        if (res.code === 0) {
          this.props.history.push('/works/my')
        } else {
          message.error(res.info)
        }
      })
    } else {
      post('dashboard/student/designwork/create', data).then((res) => {
        if (res.code === 0) {
          this.props.history.push('/Myworks')
        } else {
          message.error(res.info)
        }
      })
    }
  }
  onChangeTop = (e) => {
    this.classlists(e)
  }
  render() {
    const { location, i18n } = this.props
    const { initialValues, mockData, mockDataclass, Myhomework } = this.state
    const formProps = {
      name: 'basic',
      onFinish: this.handleSaveBtn,
      initialValues,
      ref: this.formRef,
    }

    return (
      <div style={{ height: '100%' }}>
        <div
          style={{
            height: '100%',
            position: 'fixed',
            top: '30px',
            left: '30px',
            right: '30px',
            Button: '30px',
          }}
        >
          <div style={{ position: 'relative', height: '100%' }}>
            <div
              style={{
                display: 'flex',
                width: '96%',
                justifyContent: 'center',
                zIndex: 5,
                position: 'relative',
                marginBottom: '68px',
                marginLeft: '2%',
                height: '100%',
              }}
            >
              <div>
                <img
                  style={{
                    width: '100%',
                    height: '90%',
                  }}
                  alt=""
                  src={require('../../../imges/NL1.png')}
                />
              </div>
              <div>
                <img
                  style={{
                    width: '100%',
                    height: '90%',
                  }}
                  alt=""
                  src={require('../../../imges/NL2.png')}
                />
              </div>
            </div>
            <div className="ban1">
              <div className="add">
                <div
                  style={{
                    margin: '15px 0',
                    display: 'flex',
                    alignItems: 'center',
                  }}
                >
                  <div
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      height: '64px',
                      cursor: 'pointer',
                    }}
                    onClick={() => this.clFna(1)}
                  >
                    <img
                      style={{
                        width: '48px',
                        height: '48px',
                      }}
                      alt=""
                      src={require('../../../imges/fanhui.png')}
                    />
                    <Button
                      type="link"
                      onClick={() => this.clFna(1)}
                      style={{
                        width: '40px',
                        height: '64px',
                        fontWeight: '500',
                        fontSize: '20px',
                        color: '#064764',
                        lineHeight: '30px',
                        textAlign: 'left',
                        fontStyle: 'normal',
                        marginRight: '22px',
                      }}
                    >
                      返回
                    </Button>
                  </div>
                  {this.props.match.params.id &&
                    this.props.match.params.id != 0 &&
                    (Myhomework == 0 || Myhomework == 2) ? (
                    ''
                  ) : (
                    <div
                      onClick={this.Derive}
                      style={{
                        position: 'relative',
                        cursor: 'pointer',
                        margin: '0 15px',
                      }}
                    >
                      <img
                        style={{
                          width: '260px',
                          height: '64px',
                        }}
                        alt=""
                        src={require('../../../imges/tijiao.png')}
                      />
                      <div className="liyi">立即提交作业</div>
                    </div>
                  )}{' '}
                  <div
                    onClick={this.Derive1}
                    style={{
                      position: 'relative',
                      cursor: 'pointer',
                      margin: '0 15px',
                    }}
                  >
                    <img
                      style={{
                        width: '260px',
                        height: '64px',
                      }}
                      alt=""
                      src={require('../../../imges/tijiao.png')}
                    />
                    <div className="liyi">查看我的作品</div>
                  </div>
                  <div
                    onClick={this.Derive2}
                    style={{
                      position: 'relative',
                      cursor: 'pointer',
                      margin: '0 15px',
                    }}
                  >
                    <img
                      style={{
                        width: '260px',
                        height: '64px',
                      }}
                      alt=""
                      src={require('../../../imges/tijiao.png')}
                    />
                    <div className="liyi">班级作品展区</div>
                  </div>
                </div>
              </div>
            </div>
            <div className="ban12">
              <iframe
                ref={this.iframeRef}
                src="https://online.mpython.cn/"
                width="100%"
                height="800px"
                frameborder="0"
                title="mPython"
                id="iframeContent"
              ></iframe>
            </div>
          </div>
        </div>
        <div>
          <div
            style={{
              display: 'flex',
              position: 'absolute',
              bottom: '0px',
              width: '100%',
              zIndex: 8,
            }}
          >
            <div style={{ width: '20%' }}>
              <img
                style={{
                  width: '100%',
                  height: '65px',
                }}
                alt=""
                src={require('../../../imges/db2.png')}
              />
            </div>
            <div style={{ width: '60%' }}>
              <img
                style={{
                  width: '100%',
                  height: '65px',
                }}
                alt=""
                src={require('../../../imges/db3.png')}
              />
            </div>
            <div style={{ width: '20%' }}>
              <img
                style={{
                  width: '100%',
                  height: '65px',
                }}
                alt=""
                src={require('../../../imges/db1.png')}
              />
            </div>
          </div>
        </div>
        <Modal
          width="25%"
          title="课程内容"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form {...layoutModel} {...formProps}>
            <Form.Item
              label="作业名称"
              name="designwork_name"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input className="Ip_80" />
            </Form.Item>
            <Form.Item
              label="课堂名称"
              name="classroom_id"
              rules={[
                {
                  required: true,
                  message: '请输入所属课堂名称',
                },
              ]}
            >
              <Select className="Ip_80">
                {mockDataclass.map((item) => (
                  <Select.Option key={item.id} value={item.id}>
                    {item.classroom_name}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
userDer.propTypes = {
  post: PropTypes.object,
  loading: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
}
export default userDer
